package com.fanshuai.queue;

public class LinkedQueue<E> implements Queue<E> {
    class Node<E> {
        E data;
        Node<E> pre;
        Node<E> next;

        Node(E data) {
            this.data = data;
            this.pre = null;
            this.next = null;
        }

        Node() {
            this.data = null;
            this.pre = null;
            this.next = null;
        }
    }

    private Node<E> head;
    private Node<E> tail;
    private int size;

    public LinkedQueue() {
        Node<E> node = new Node<>();
        head = node;
        tail = node;
        size = 0;
    }

    @Override
    public int size() {
        return size;
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
    }

    @Override
    public boolean isFull() {
        return false;
    }

    @Override
    public void enqueue(E data) {
        Node<E> node = new Node<>(data);
        tail.next = node;
        node.pre = tail;

        tail = node;
        size++;
    }

    @Override
    public E dequeue() {
        if (isEmpty()) {
            throw new IndexOutOfBoundsException("queue empty");
        }

        Node<E> node = head.next;

        head.next = node.next;
        if (node.next != null) {
            node.next.pre = head;
        }

        E data = node.data;

        if (node.next == null) {
            tail = node.pre;
        }

        node.next = null;
        node.pre = null;
        node.data = null;
        size--;

        return data;
    }

    @Override
    public E peek() {
        Node<E> node = head.next;
        return null == node ? null : node.data;
    }
}


